package org.sxp.modules.sys.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.sxp.common.exception.BusinessException;
import org.sxp.common.web.WrapperResponse;
import org.sxp.modules.oss.entity.SysOssEntity;
import org.sxp.modules.oss.service.SysOssService;
import org.sxp.modules.sys.entity.SysConfigEntity;
import org.sxp.modules.sys.entity.SysUserEntity;
import org.sxp.modules.sys.service.SysConfigService;
import org.sxp.modules.sys.service.SysUserService;
import org.sxp.modules.sys.shiro.ShiroUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;

/**
 * 登录相关
 *
 *
 */
@Controller
@ConditionalOnProperty(prefix = "shiro", name = "type", havingValue = "cookie")
public class SysLoginController {
	@Autowired
	private Producer producer;

	@Autowired
	SysConfigService configService;

	@Autowired
	private SysUserService userService;

	public static String system_name_config_key = "system_name";
	public static String system_bg_config_key = "system_bg";
	public static String login_style_config_key = "login_style";

	@Autowired
	private SysOssService ossService;
	
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public WrapperResponse login(String username, String password, String captcha) {
		
		try{
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			subject.login(token);
		}catch (UnknownAccountException e) {
			throw new BusinessException("账号不存在");
		}catch (IncorrectCredentialsException e) {
			SysUserEntity userEntity = userService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUsername, username));
			if(userEntity != null){
				userEntity.setLoginErrorNum(userEntity.getLoginErrorNum() + 1);
				userService.update(
						new LambdaUpdateWrapper<SysUserEntity>()
								.set(SysUserEntity::getLoginErrorNum, userEntity.getLoginErrorNum())
								.set(SysUserEntity::getLoginTime, new Date())
								.eq(SysUserEntity::getUserId, userEntity.getUserId())
				);
			}

			throw new BusinessException(userEntity != null ? "密码不正确，错误次数：" + userEntity.getLoginErrorNum() + "/6" : "账号或密码错误");
		}catch (LockedAccountException e) {
			throw new BusinessException("账号已被锁定,请联系管理员");
		}catch (AuthenticationException e) {
			throw new BusinessException(e.getMessage());
		}
	    
		return WrapperResponse.success(null);
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login";
	}

	@RequestMapping(value = {"/login"})
	public String getLoginPage(Model model){
		String name = configService.getValue(system_name_config_key);
		String bg = configService.getValue(system_bg_config_key);
		String loginStyle = configService.getValue(login_style_config_key);
		if(StringUtils.isBlank(name)){
			name = "DataHub";
			SysConfigEntity configEntity = new SysConfigEntity();
			configEntity.setParamKey(system_name_config_key);
			configEntity.setParamValue(name);
			configService.saveConfig(configEntity);
		}
		if(StringUtils.isNotBlank(bg)){
			SysOssEntity ossEntity = ossService.getById(bg);
			if(ossEntity != null){
				bg = "background: url(data:image/jpeg;base64," + Base64Utils.encodeToString(ossEntity.getData()) + ") center center no-repeat";
			}
		}
		if(!StrUtil.contains(bg, "background:")){
			bg = "background: url(backup.jpg) center center no-repeat";
		}
		model.addAttribute("systemBg", bg);
		model.addAttribute("systemName", name);
		model.addAttribute("loginStyle", loginStyle);
		return "login";
	}
	
}
